package com.vhall.component.framework.support;

import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.framework.common.exception.ExceptionResult;
import com.vhall.component.framework.common.exception.GlobalErrorCode;
import com.vhall.component.framework.common.utils.RequestAnalysor;
import com.vhall.component.framework.common.utils.Throwabler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.util.List;

/**
 * 异常处理实现类
 *
 * @author xiaoliang.wang@vhall.com
 */
@Slf4j
@RestControllerAdvice
public class VhallExceptionHandler {


    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ExceptionResult businessException(HttpServletRequest request, BusinessException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        return new ExceptionResult(e.getKey(), e.getMessage(), e.getCode(), uri).setThrowable(e);
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ExceptionResult validationException(HttpServletRequest request, BindException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        String defaultMessage = e.getAllErrors().get(0).getDefaultMessage();
        // 在这里判断是类型转换异常还是校验异常
        assert defaultMessage != null;
        if (defaultMessage.contains("Exception")) {
            FieldError objectError = (FieldError) e.getAllErrors().get(0);
            String field = objectError.getField();
            String fieldNew = field.replaceAll("[A-Z]", "_$0").toLowerCase();
            return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), fieldNew + "参数格式错误！", 60000, uri).setThrowable(e);
        }
        return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), defaultMessage, 60000, uri).setThrowable(e);
    }

    /**
     * 抛出NumberFormatException
     *
     * @param request
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public ExceptionResult validationNumException(HttpServletRequest request, MethodArgumentTypeMismatchException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        String fieldNew = e.getName().replaceAll("[A-Z]", "_$0").toLowerCase();
        return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), fieldNew + "参数格式错误！", 60000, uri).setThrowable(e);
    }

    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ExceptionResult argumentException(HttpServletRequest request, IllegalArgumentException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), "参数错误: " + e.getMessage(), 60000, uri).setThrowable(e);
    }

    @ResponseBody
    @ExceptionHandler(value = ConnectException.class)
    public ExceptionResult connectException(HttpServletRequest request, ConnectException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        Integer code = HttpStatus.GATEWAY_TIMEOUT.value();

        return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), "无法连接到远程服务器。", code, uri).setThrowable(e);
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ExceptionResult methodArgumentNotValidException(HttpServletRequest request,
                                                           MethodArgumentNotValidException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        String message = errorMsg.toString();
        Integer code = HttpStatus.BAD_REQUEST.value();

        return new ExceptionResult(GlobalErrorCode.FAILED.getKey(), message, code, uri).setThrowable(e);
    }

    @ResponseBody
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ExceptionResult noHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        Integer code = HttpStatus.NOT_FOUND.value();
        return new ExceptionResult("failed", "无此路由！", code, uri).setThrowable(e);
    }


    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ExceptionResult defaultException(HttpServletRequest request, Exception e) {
        log.error("Exception", e);
        String uri = RequestAnalysor.getUri(request);
        String stackTrace = Throwabler.getFirstStackInfo(e);
        Integer code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        String msg = "系统异常";
        String key = "failed";
        Throwable thr = e.getCause();
        if (thr instanceof InvocationTargetException) {
            Throwable bizExp = ((InvocationTargetException) thr).getTargetException();
            if (bizExp instanceof BusinessException) {
                BusinessException bizExp1 = (BusinessException) bizExp;
                code = bizExp1.getCode() == null ? 60000 : bizExp1.getCode();
                msg = StringUtils.isBlank(bizExp1.getMsg()) ? bizExp1.getMessage() : bizExp1.getMsg();
                key = StringUtils.isBlank(bizExp1.getKey()) ? key : bizExp1.getKey();
                return new ExceptionResult(key, msg, code, uri).setThrowable(e);
            } else if (bizExp instanceof IllegalArgumentException) {
                IllegalArgumentException illegalArgumentException = (IllegalArgumentException) bizExp;
                msg = StringUtils.isNotBlank(illegalArgumentException.getMessage()) ? illegalArgumentException.getMessage() : msg;
                return new ExceptionResult(key, msg, code, uri).setThrowable(e);
            }
        } else if (thr instanceof BusinessException) {
            BusinessException bizExp1 = (BusinessException) thr;
            code = bizExp1.getCode() == null ? 60000 : bizExp1.getCode();
            msg = StringUtils.isBlank(bizExp1.getMsg()) ? bizExp1.getMessage() : bizExp1.getMsg();
            key = StringUtils.isBlank(bizExp1.getKey()) ? key : bizExp1.getKey();
            return new ExceptionResult(key, msg, code, uri).setThrowable(e);
        }
        return new ExceptionResult(key, msg, code, uri).setThrowable(e);
    }
}
